package lecode;

import java.util.Arrays;
import java.util.HashMap;

/**
 * 示例 1：
 *
 * 输入：nums = [2,7,11,15], target = 9
 * 输出：[0,1]
 * 解释：因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。
 * 示例 2：
 *
 * 输入：nums = [3,2,4], target = 6
 * 输出：[1,2]
 * 示例 3：
 *
 * 输入：nums = [3,3], target = 6
 * 输出：[0,1]
 */
public class 两数之和1 {

    public static void main(String[] args) {
        int[] nums = {2,7,11,15};
        int target = 9;
        int[] ints = twoSum(nums,target);
        System.out.println(Arrays.toString(ints));

        System.out.println("-------------------");
        int[] ints1 = hashTwoSum(nums, target);
        System.out.println(Arrays.toString(ints1));
    }


    /**
     * 第一种，暴力破解
     */
    public static  int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                }
            }
        }

        return result;
    }


    /**
     * 第二种 哈希表法
     */
    public static  int[] hashTwoSum(int[] nums, int target) {
        int[] result = new int[2];//[2,7,11,15]
        HashMap<Integer, Integer> tagMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
           int flag   = target - nums[i];
           if (tagMap.containsKey(flag)) {
               result[0] = tagMap.get(flag);
               result[1] = i;
               return result;
           }else {
               tagMap.put(nums[i],i);
           }
        }

        return result;
    }
}
